<template>
  <el-dialog
    :title="state.info.id ? '修改分类' : '添加分类'"
    v-model="visible"
    @close="handleClose"
  >
    <el-form :model="state.info" :rules="rules" ref="formRef" label-width="120px">
      <el-form-item label="分类名称" prop="info.title">
        <el-input type="text" v-model="state.info.title"></el-input>
      </el-form-item>
      <el-form-item label="排序值" prop="info.orderby">
        <el-input type="number" max='200' v-model="state.info.orderby"></el-input>
      </el-form-item>
      <el-form-item label="是否隐藏" prop="info.hide">
        <el-switch class="el-switch-prompt" v-model="state.info.hide"
          :active-value="1"
          :inactive-value="2"
          :inline-prompt="true"
          active-text="显示"
          inactive-text="隐藏">
        </el-switch>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { reactive, ref } from 'vue'
import { useRoute } from 'vue-router'
import { hasEmoji } from '../utils'
import { ElMessage } from 'element-plus'
import { AdminGoodsCategoryInfo, AdminGoodsCategoryPost, AdminGoodsCategoryPut } from "../api/server/goods/category";

const props = defineProps({
  reload: Function
})

const formRef = ref(null)
const route = useRoute()
const visible = ref(false)
const state = reactive({
  info: {
    title: '',
    hide: 1,
    orderby: 0,
  }
})
const rules = reactive({
  title: [
    { required: 'true', message: '分类名称不能为空', trigger: ['change'] }
  ],
})


// 开启弹窗
const open = (id) => {
  visible.value = true
  if (id) {
    state.info.id = id
    AdminGoodsCategoryInfo(id).then(({ data: { info } }) => {
      state.info = info
    })
  } else {
    state.info = {
      title: '',
      hide: 1,
      orderby: 0,
    }
  }
}

// 关闭弹窗
const close = () => {
  visible.value = false
  formRef.value.resetFields()
}
const handleClose = () => {
  formRef.value.resetFields()
}
const submitForm = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      if (hasEmoji(state.info.title)) {
        ElMessage.error('分类名称中包含表情符号')
        return
      }
      if (state.info.title.length > 16) {
        ElMessage.error('分类名称不能超过16个字符')
        return
      }

      if (!state.info.id) {
        await AdminGoodsCategoryPost(state.info)
        ElMessage.success('添加成功')
      } else {
        await AdminGoodsCategoryPut(state.info.id, state.info)
        ElMessage.success('更新成功')
      }
      visible.value = false
      if (props.reload) props.reload()
    }
  })
}

defineExpose({ open })
</script>

